package com.str.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.str.utils.RedisUtil;
import com.str.vo.SystemUserVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * @Author: ZhangWu, Anything is possible!
 * @CreateTime: 2023/04/09 15:10
 * @Description: 系统过滤器
 */


@Log4j2
@WebFilter(filterName = "AuthenticationFilter", urlPatterns = "/*")
@Component
public class AuthenticationFilter implements Filter {


    @Resource
    private RedisUtil redisUtil;


    //忽略请求地址
    public List<String> ignoreUrl
            = Arrays.asList(
            "/systemUser/getKey",
            "/systemUser/submit",
            "/systemUser/getLoginCode",
            "/swagger-ui/**",
            "/swagger*/**",
            "/favicon.ico",
            "/swagger-resources",
            "/swagger-ui/index.html",
            "/swagger-ui/swagger-ui.css",
            "/swagger-ui/swagger-ui-bundle.js",
            "/swagger-resources/**",
            "/swagger-ui/springfox.css",
            "/swagger-ui/springfox.js",
            "/doc.html",
            "/swagger-ui",
            "/swagger-resources/configuration/security",
            "/swagger-resources/configuration/ui",
            "/swagger-ui/swagger-ui-standalone-preset.js",
            "/swagger-ui/swagger-ui.css.map"
            , "/webjars/**"
            , "/v3/api-docs"
            , "/v2/api-docs");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("AuthenticationFilter---->init()");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        //获取请求URI
        String requestURI = httpRequest.getRequestURI();
        if (ignoreUrl.contains(requestURI)) {
            //放行
            filterChain.doFilter(httpRequest, httpResponse);
        } else {
            // 从 http 请求头中取出 token
            String token = httpRequest.getHeader("X-Token");
            //没有token
            if (StringUtils.isBlank(token)) {
                httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                httpResponse.setContentType("application/json; charset=UTF-8");
                httpResponse.getOutputStream().write("token不能为空！".getBytes(StandardCharsets.UTF_8));
            } else{
                // 判断token是否过期
                SystemUserVO systemUserVO = redisUtil.get(token, SystemUserVO.class);
                String redisToken = Objects.nonNull(systemUserVO) ? systemUserVO.getToken() : null;
                if (!token.equals(redisToken)) {
                    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    httpResponse.setContentType("application/json; charset=UTF-8");
                    httpResponse.getOutputStream().write("登录已过期，请重新登录！".getBytes(StandardCharsets.UTF_8));
                }else {
                    //放行
                    filterChain.doFilter(httpRequest, httpResponse);
                }
            }
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
